package com.example.courseapp.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.courseapp.R;
import com.example.courseapp.RetrofitHelper;
import com.example.courseapp.SharedPreferencesHelper;
import com.example.courseapp.activity.AddChildActivity;
import com.example.courseapp.adapter.ChildAdapter;
import com.example.courseapp.bean.ChildInformation;
import com.example.courseapp.net.CourseService;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class HealthFragment extends Fragment {


    public HealthFragment() {}


    public static HealthFragment newInstance() {
        return new HealthFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


    }
    CourseService service;

    ChildAdapter childAdapter = new ChildAdapter();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_resource, container, false);

        service = RetrofitHelper.getInstance().createService(CourseService.class);

        RecyclerView recyclerView = view.findViewById(R.id.recycler);

        recyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));

        recyclerView.setAdapter(childAdapter);


        Button button = view.findViewById(R.id.addChild);
        button.setOnClickListener(v -> {
            Intent intent = new Intent(requireActivity(), AddChildActivity.class);
            startActivity(intent);
        });

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        Integer userID = Integer.valueOf(SharedPreferencesHelper.getName(requireContext(),"userID"));
        service.getChildList(userID).enqueue(new Callback<List<ChildInformation>>() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onResponse(@NonNull Call<List<ChildInformation>> call, @NonNull Response<List<ChildInformation>> response) {
                requireActivity().runOnUiThread(() -> {


                    childAdapter.bindData(response.body());
                    childAdapter.notifyDataSetChanged();
                });

            }

            @Override
            public void onFailure(Call<List<ChildInformation>> call, Throwable t) {

            }
        });
    }
}